//
//  HZL_StoreDetailViewController.m
//  B_Project
//
//  Created by dllo on 15/11/25.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_StoreDetailViewController.h"
#import "HZL_StoreDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "HZL_NetworkingHandle.h"
#import "HZL_MapViewController.h"
#import "HZL_SizeModel.h"
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
static CGFloat kImageOriginHight = 250;
@interface HZL_StoreDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *expandZoomImageView; // 背景图
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, strong) NSString *webUrl;
@property (nonatomic, retain) NSMutableArray *areaArr;
@property (nonatomic, retain) NSMutableDictionary *dataDic;
@property (nonatomic, retain) UIImageView *left;
@property (nonatomic, retain) UIImageView *right;
@property (nonatomic, retain) NSMutableDictionary *address;
@property (nonatomic, copy) NSString *longitude;
@property (nonatomic, copy) NSString *latitude;

@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain) NSArray *likeArr;
@property (nonatomic, assign) BOOL isLike;
@end

@implementation HZL_StoreDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.manager = [CoreDataManager shareInstance];
    NSLog(@"%@", [self.manager applicationDocumentsDirectory]);
//    [self creatTableView];
    [self getData];
    [self creatWebView];
    
    [self loadMBProgress];
}
#pragma mark - 视图要出现时候 隐藏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.alpha = 0.0;
    self.navigationController.navigationBar.hidden = YES; //如果不写 从其他页过来 会出现一个navagationBar
    
    [self searchLike];
    
    if (self.model) {
        for (Store *s in self.likeArr) {
            if ([s.businessId isEqualToString:self.model
                .businessId]) {
                self.isLike = YES;
            }else {
                self.isLike = NO;
            }
        }
    }
    if (self.findModel) {
        for (Find *f in self.likeArr) {
            if ([f.iD isEqualToString:self.findModel.iD]) {
                self.isLike = YES;
            }else {
                self.isLike = NO;
            }
        }
    }
}

#pragma mark - 创建tableView
- (void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT + 49) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.contentInset = UIEdgeInsetsMake(kImageOriginHight, 0, 0, 0);
    [self.view addSubview:self.tableView];
    
    
    
    // 背景图
    self.expandZoomImageView = [[UIImageView alloc]init];
    if (self.model) {
        [self.expandZoomImageView sd_setImageWithURL:[NSURL URLWithString:self.model.img]];
    }else {
        [self.expandZoomImageView sd_setImageWithURL:[NSURL URLWithString:self.findModel.img]];
    }
    
    self.expandZoomImageView.contentMode = UIViewContentModeScaleToFill;
    self.expandZoomImageView.frame = CGRectMake(0, -kImageOriginHight, [UIScreen mainScreen].bounds.size.width , kImageOriginHight);
    self.expandZoomImageView.userInteractionEnabled = YES;
    [self.tableView addSubview:self.expandZoomImageView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(10, 20, 40, 40)];
    btn.backgroundColor = [UIColor clearColor];
    [self.expandZoomImageView addSubview:btn];
    [btn setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(go) forControlEvents:UIControlEventTouchUpInside];
    
    // 类型
    UILabel *type = [[UILabel alloc] initWithFrame:CGRectMake(10, -(kImageOriginHight - 170), VIEW_WIDTH - 20, 20)];
    type.textColor = [UIColor whiteColor];
    type.text = @"FollowMe";
    type.font = [UIFont fontWithName:@"GillSans-SemiBold" size:18];

//    type.font = [UIFont boldSystemFontOfSize:15];
    [self.tableView addSubview:type];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(10, -(kImageOriginHight - 190), VIEW_WIDTH - 40, 1)];
    line.backgroundColor = [UIColor whiteColor];
    line.font = [UIFont systemFontOfSize:12];
    [self.tableView addSubview:line];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, -(kImageOriginHight - 190), VIEW_WIDTH - 20, 40)];
    
    if (self.model) {
        title.text = self.model.title;
    }else {
        title.text = self.findModel.name;
    }
    title.textColor = [UIColor whiteColor];
    title.font = [UIFont fontWithName:@"GillSans-UltraBold" size:24];
    [self.tableView addSubview:title];
    
    // 收藏按钮
    UIButton *collectionBT = [UIButton buttonWithType:UIButtonTypeCustom];
    if (self.isLike == YES) {
        [collectionBT setImage:[UIImage imageNamed:@"bottom_btn_liked@2x"] forState:UIControlStateNormal];
    }else {
        [collectionBT setImage:[UIImage imageNamed:@"bottom_btn_like@2x"] forState:UIControlStateNormal];
    }
    collectionBT.tag = 1000;
    [collectionBT addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    collectionBT.frame = CGRectMake(VIEW_WIDTH - 70, - 20, 40, 40);
    [self.tableView addSubview:collectionBT];
    
    // 双引号
    if (self.model) {
        UIImageView *left = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 20, 20)];
        left.image = [UIImage imageNamed:@"iconfont-qianyinhao"];
        [self.tableView addSubview:left];
        UIImageView *right = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 30, 160, 20, 20)];
        right.image = [UIImage imageNamed:@"iconfont-houyinhao"];
        [self.tableView addSubview:right];
    }
    
    // 电话地址
    if (self.model) {
        UIImageView *place = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 50, 225, 25, 25)];
        place.image = [UIImage imageNamed:@"iconfont-dizhi"];
        [self.tableView addSubview:place];
        UIImageView *phone = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 50, 265, 28, 28)];
        phone.image = [UIImage imageNamed:@"iconfont-dianhua-3"];
        [self.tableView addSubview:phone];
    }else {
        UIImageView *place = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 50, 45, 25, 25)];
        place.image = [UIImage imageNamed:@"iconfont-dizhi"];
        [self.tableView addSubview:place];
        UIImageView *phone = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 50, 85, 28, 28)];
        phone.image = [UIImage imageNamed:@"iconfont-dianhua-3"];
        [self.tableView addSubview:phone];
    }
    // 初始化
    
}
- (void)go
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 收藏
- (void)likeAction:(UIButton *)btn
{
    if (self.isLike == YES) {
        [self deleteLike];
        self.isLike = NO;
        [btn setImage:[UIImage imageNamed:@"bottom_btn_like@2x"] forState:UIControlStateNormal];
    }else {
        if (self.model) {
            Store *store = [NSEntityDescription insertNewObjectForEntityForName:@"Store" inManagedObjectContext:self.manager.managedObjectContext];
            store.title = self.model.title;
            store.img = self.model.img;
            store.descr = self.model.descr;
            store.businessId = self.model.businessId;
            [[CoreDataManager shareInstance] saveContext];
        }else {
            Find *find = [NSEntityDescription insertNewObjectForEntityForName:@"Find" inManagedObjectContext:self.manager.managedObjectContext];
            find.name = self.findModel.name;
            find.img = self.findModel.img;
            find.iD = self.findModel.iD;
            find.desc = self.findModel.desc;
            [[CoreDataManager shareInstance] saveContext];
        }
        [btn setImage:[UIImage imageNamed:@"bottom_btn_liked@2x"] forState:UIControlStateNormal];
        self.isLike = YES;
        NSLog(@"收藏");
    }
}
#pragma mark - 删除收藏
- (void)deleteLike
{
    [self searchLike];
    if (self.model) {
        for (Store *s in self.likeArr) {
            if ([s.businessId isEqualToString:self.model.businessId]) {
                [self.manager.managedObjectContext deleteObject:s];
            }
            [self.manager saveContext];
        }
    }else {
        for (Find *f in self.likeArr) {
            if ([f.iD isEqualToString:self.findModel.iD]) {
                [self.manager.managedObjectContext deleteObject:f];
            }
            [self.manager saveContext];
        }
    }
}
#pragma mark - 搜索收藏
- (void)searchLike
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    if (self.model) {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Store" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
    }else {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Find" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
    }
    // Specify criteria for filtering which objects to fetch
    
    if (self.model) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"businessId = %@", self.model.businessId];
        [fetchRequest setPredicate:predicate];
    }else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iD = %@", self.findModel.iD];
        [fetchRequest setPredicate:predicate];
    }
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    }
    // 获取查找到的数组
    self.likeArr = [NSArray arrayWithArray:fetchedObjects];
}
#pragma mark - 获取数据
- (void)getData
{
    NSString *url = @"http://www.molyo.com/mShop/getInfoV1_7";
    if (self.model) {
         NSString *body = [NSString stringWithFormat:@"device=iPhone7%%2C2&id=%@&netWork=wifi&os=ios%%209.100000", self.model.businessId];
        [HZL_NetworkingHandle requestPOSTWithURl:url body:body completion:^(id result) {
            self.hud.hidden = YES;
            [self.hud removeFromSuperview];
            NSLog(@"%@", result);
            self.longitude = result[@"body"][@"longitude"];
            self.latitude = result[@"body"][@"latitude"];
            self.address = result[@"body"];
            
            NSString *str1 = [NSString stringWithFormat:@"地址:   %@", result[@"body"][@"address"]];
            
            NSString *str2 = [NSString stringWithFormat:@"电话:   %@", result[@"body"][@"phone"]];
            NSString *str3 = [NSString stringWithFormat:@"类型:   %@",result[@"body"][@"category"][0][@"name"]];
            self.areaArr = [NSMutableArray arrayWithObjects:str1, str2, str3, nil];
            [self creatTableView];
        }];
    }else {
         NSString *body = [NSString stringWithFormat:@"device=iPhone7%%2C2&id=%@&netWork=wifi&os=ios%%209.100000", self.findModel.iD];
        [HZL_NetworkingHandle requestPOSTWithURl:url body:body completion:^(id result) {
            self.hud.hidden = YES;
            [self.hud removeFromSuperview];
    
            self.longitude = result[@"body"][@"longitude"];
            self.latitude = result[@"body"][@"latitude"];
            self.address = result[@"body"];
            
            NSString *str1 = [NSString stringWithFormat:@"地址:   %@", result[@"body"][@"address"]];
            
            NSString *str2 = [NSString stringWithFormat:@"电话:   %@", result[@"body"][@"phone"]];
            NSString *str3 = [NSString stringWithFormat:@"类型:   %@",result[@"body"][@"category"][0][@"name"]];
            self.areaArr = [NSMutableArray arrayWithObjects:str1, str2, str3, nil];
            [self creatTableView];
        }];
    }
    
    
}
#pragma mark - 创建webView
- (void)creatWebView
{ 
    // webView
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    self.webView.delegate = self;
    self.webView.scrollView.scrollEnabled = NO;
    
    
    if (self.model) {
        self.webUrl = [NSString stringWithFormat:@"http://www.molyo.com/mShop/tip/info?shopId=%@&hasTip=1&netWork=wifi", self.model.businessId];
    }else {
        self.webUrl = [NSString stringWithFormat:@"http://www.molyo.com/mShop/tip/info?shopId=%@&hasTip=1&netWork=wifi", self.findModel.iD];
    }
    //预先加载url
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.webUrl]]];
}

#pragma mark - tableView方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return 3;
    } else {
        return 1;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 创建一个视图（v_headerView）
    UIView *v_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, VIEW_WIDTH, 30)];
    //创建一个UILable（v_headerLab）用来显示标题
    if (!(section == 0)) {
        UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, -20, 50, 25)];
        locationLabel.backgroundColor = [UIColor redColor];
        locationLabel.textColor = [UIColor whiteColor];
        locationLabel.textAlignment = NSTextAlignmentCenter;
        locationLabel.font = [UIFont fontWithName:@"Arial" size:16];
        locationLabel.font = [UIFont boldSystemFontOfSize:16];
        locationLabel.shadowColor = [UIColor whiteColor];
        [locationLabel setShadowOffset:CGSizeMake(0, 1)];
        [v_headerView addSubview:locationLabel];
        if (section == 1) {
            locationLabel.text = @"地址" ;
        } if (section == 2) {
            locationLabel.text = @"特色";
        }
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 9, VIEW_WIDTH - 30, 1.5)];
        line.backgroundColor = [UIColor blackColor];
        [v_headerView addSubview:line];

    }
    
    return v_headerView;
}
#pragma mark - tableView赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 1) {
        static NSString *identifier = @"location";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.textLabel.text = self.areaArr[indexPath.row];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        return cell;
    }
    if (indexPath.section == 2){
        static NSString *identifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            [cell.contentView addSubview:_webView];
            /* 忽略点击效果 */
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        return cell;
    } else {
        static NSString *identifier = @"cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            [cell.contentView addSubview:self.left];
        }
        cell.selectionStyle = UITableViewCellAccessoryNone;
        
        if (self.model) {
            cell.textLabel.text = [NSString stringWithFormat:@"      %@", self.model.descr];
        }else {
            cell.textLabel.text = [NSString stringWithFormat:@"      %@", self.findModel.desc];
        }
        cell.textLabel.numberOfLines = 0;
        return cell;
    }
}

#pragma mark - tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            HZL_MapViewController *map = [[HZL_MapViewController alloc] init];
            map.longitude = self.longitude;
            map.latitude = self.latitude;
            map.address = self.address;
            self.navigationController.navigationBar.hidden = NO;
            [self.navigationController pushViewController:map animated:YES];
        } if (indexPath.row == 1) {
            [self phoneAction];
        }
    }
}
#pragma mark - 打电话
- (void)phoneAction
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否拨打电话" message:self.areaArr[1] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *canelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        // 点击取消按钮执行的代码
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 点击确定按钮执行的代码
        NSString *telStr = [NSString stringWithFormat:@"tel://%@",self.areaArr[1]];
        NSURL *url = [NSURL URLWithString:telStr];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"号码不可用\n或您的备设不支持拨号功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *canelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                // 点击取消按钮执行的代码
            }];
            [alert addAction:canelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    }];
    // 给alert添加操作
    [alert addAction:canelAction];
    [alert addAction:okAction];
    // 模态显示
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        // 通过webview代理获取到内容高度后,将内容高度设置为cell的高
        return _webView.frame.size.height;
    } if (indexPath.section == 1) {
        return 40;
    } else {
        if (self.model) {
            
            return 180;
        }else {
            
            return 0;
        }
    }
}

#pragma mark - webView代理方法
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 获取到webview的高度
//    [self.hud removeFromSuperview];

    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, kScreenWidth, height);
    [self.tableView reloadData];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    NSLog(@"webViewDidStartLoad");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    NSLog(@"didFailLoadWithError===%@", error);
}

#pragma mark - 滑动时拉大图片方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset  = scrollView.contentOffset.y ;
    CGFloat xOffset = (yOffset + kImageOriginHight)/2;
    if (yOffset < -kImageOriginHight) {
        CGRect f = self.expandZoomImageView.frame;
        f.origin.y = yOffset ;
        f.size.height =  -yOffset ;
        f.origin.x = xOffset;
        f.size.width = VIEW_WIDTH + fabs(xOffset)*2;
        self.expandZoomImageView.frame = f;
    }
    
    
    //获取当前偏移量
//    CGFloat y = scrollView.contentOffset.y;
    //bar 将要出来时  显隐度一点点改变
    if (scrollView.contentOffset.y <= 0 && scrollView.contentOffset.y >= -64) {
        self.navigationController.navigationBar.alpha = (64 + scrollView.contentOffset.y) / 64;
        self.navigationController.navigationBar.hidden = NO;
    }
    else if (scrollView.contentOffset.y > 0)
    {
        self.navigationController.navigationBar.alpha = 1.0;
        //        self.navigationController.navigationBar.hidden = NO;
    }
    else
    {
        self.navigationController.navigationBar.alpha = 0.0;
        //        self.navigationController.navigationBar.hidden = YES;
    }
}
#pragma mark - 视图要消失时候 设置bar出现
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.alpha = 1.0;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
